<template>
  <div class="page">
    <div class="box flex flex-rr pt-30 pb-0">
      <lang-comp></lang-comp>
    </div>

    <div class="box">
      <!-- 顶部栏 -->
      <div class="flex flex-cc flex-rb mb-30">
        <img style="width: 120px" src="../assets/img/logo.png" />
        <div class="address flex flex-cc">
          <img
            class="mr-10"
            style="width: 20px"
            src="../assets/img/icon_wallet.png"
          />
          <div>{{ fromAddressHideRef }}</div>
        </div>
      </div>

      <!-- 钱包余额 -->
      <div class="mb-30">
        <div class="flex">
          <div style="width: 50%">
            <div class="tag">PC</div>
            <div class="mt-10 mb-10">
              <span class="fz-24 fw-bold">
                {{ getBalanceFirst(pcBalance) }}
              </span>
              <span class="fz-12 fw-100">.{{ getBalanceLast(pcBalance) }}</span>
            </div>
          </div>

          <div style="width: 50%">
            <div class="tag">PSPT</div>
            <div class="mt-10 mb-10">
              <span class="fz-24 fw-bold">
                {{ getBalanceFirst(psptBalance) }}
              </span>
              <span class="fz-12 fw-100">
                .{{ getBalanceLast(psptBalance) }}
              </span>
            </div>
          </div>
        </div>

        <img style="width: 100%" src="../assets/img/bd_bottom.png" />
      </div>

      <!-- 我的邀请链接 -->
      <div class="box-white mb-15" style="line-height: 1.2">
        <div class="mb-5">{{ $t('我的邀请链接') }}</div>
        <div class="cl-primary click" @click="copyString(inviteLink)">
          {{ inviteLink }}
        </div>
      </div>

      <!-- 倒计时 -->
      <div class="box-white mb-15">
        <!-- 环形进度条 -->
        <div class="flex flex-center mb-30">
          <van-circle
            color="#02cc66"
            layer-color="#e4e4e4"
            :size="200"
            :stroke-width="260"
            :rate="countProgress"
            v-model:current-rate="countProgress"
          >
            <div class="pt-70">
              <div class="tag mb-10" style="padding: 2px 10px">
                {{ $t('倒计时') }}
              </div>

              <van-count-down
                :time="countTime"
                @change="setCountProgress"
                v-if="countTime"
              ></van-count-down>

              <div v-else>{{ $t('未开启') }}</div>
            </div>
          </van-circle>
        </div>

        <div class="flex ta-center">
          <div style="width: 50%">
            <div>{{ $t('激活额度') }} U</div>
            <div class="fz-24 fw-bold">
              {{ toFixed(detail?.order?.open_u) }}
            </div>
          </div>

          <div style="width: 50%">
            <div>{{ $t('预计激活额度') }} PC</div>
            <div class="fz-24 fw-bold">
              {{ toFixed(detail?.order?.end_amount) }}
            </div>
          </div>
        </div>
      </div>

      <!-- 共识列表 -->
      <ul class="flex flex-rb flex-wrap fz-12">
        <li
          class="box-white click p-15 mb-15"
          style="width: calc(50% - 7.5px)"
          v-for="(v, i) in levels"
          :key="i"
          @click="createLevelOrder(v)"
        >
          <div class="flex flex-rr mb-5">
            <img style="width: 24px" :src="getLevelIconUrl(v.level)" />
          </div>

          <div class="bd-bottom pb-10 mb-10">
            <div>
              <span class="cl-basic mr-5">{{ $t('共识') }}</span>
              <span>{{ toFixed(v.amount) }} U</span>
            </div>
            <div>
              <span class="cl-basic mr-5">{{ $t('共识天数') }}</span>
              <span class="mr-5">{{ v.day }}</span>
              <span class="cl-basic">{{ $t('天') }}</span>
            </div>
          </div>

          <div class="flex flex-cc">
            <img
              class="mr-5"
              style="width: 10px"
              src="../assets/img/icon_circle.png"
            />
            <div>APR:{{ v.yield }}%</div>
          </div>
        </li>
      </ul>
    </div>

    <!-- Tab -->
    <div class="box bcl-white">
      <van-tabs type="card" v-model:active="tabIndex">
        <van-tab :title="$t('共识详情')" :name="0">
          <cons-comp
            @open="() => createLevelOrder('open')"
            @finish="() => createLevelOrder('finish')"
          ></cons-comp>
        </van-tab>
        <van-tab :title="$t('市场详情')" :name="1">
          <market-comp></market-comp>
        </van-tab>
        <van-tab :title="$t('收益详情')" :name="2">
          <profit-comp></profit-comp>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, provide } from 'vue'
import { useStore } from '@/store/index'
import { showToast, showLoading, toNumber, toFixed, copyString } from 'js/utils'
import cosmo from 'cosmo-wallet-tool'
import api from 'js/api'

import langComp from '../components/lang.vue'
import consComp from '../components/cons.vue'
import marketComp from '../components/market.vue'
import profitComp from '../components/profit.vue'

const store = useStore()

// 隐藏的钱包地址
const fromAddressHideRef = ref(window.fromAddressHide)

// PC余额
const pcBalance = ref(0)
const psptBalance = ref(0)

// 邀请链接
const inviteLink = ref(`${location.origin}/#/register?inviteId=${fromAddress}`)

// 共识开始时间
const startTime = computed(() => {
  if (detail.value?.order?.open_time) {
    return detail.value?.order?.open_time * 1000
  } else {
    return 0
  }
})

// 共识结束时间
const endTime = ref(0)

// 倒计时时间
const countTime = ref(0)

// 倒计时进度
const countProgress = ref(0)

// 共识详情
const detail = ref({})
provide(
  'detail',
  computed(() => detail.value)
)

// 共识列表
const levels = ref([])

// Tab索引
const tabIndex = ref(0)

initPage()

function initPage() {
  getPcBalance()
  getPsptBalance()
  getLevelDetail()
  getLevelList()
}

// 获取PC余额
async function getPcBalance() {
  const params = {
    address: window.fromAddress,
  }

  const { balance } = await api.getPcBalance(params)

  pcBalance.value = toNumber(balance.amount || 0)
}

// 获取PSPT余额
async function getPsptBalance() {
  const balance = await cosmo.chromeTool.contractCall(
    'gx1t7yadwcylshsrvzdvwvvwhd6fwze72sq7cmw97',
    'balanceOf(address)',
    [window.fromAddress]
  )

  psptBalance.value = toNumber(balance || 0)
}

// 获取共识详情
function getLevelDetail() {
  return new Promise(async (resolve) => {
    try {
      const { code, data } = await api.getLevelDetail()

      if (code === 1) {
        detail.value = data
        startCountDown()
        resolve(detail.value)
      } else {
        resolve({})
      }
    } catch (err) {
      resolve({})
    }
  })
}

// 获取共识列表
async function getLevelList() {
  const { code, data } = await api.getLevelList()

  if (code === 1) {
    levels.value = data.level || []
  }
}

// 创建共识订单
async function createLevelOrder(v) {
  // 用户等级不足
  if (store.userInfo?.level < v.level) {
    return showToast($t('用户等级不足'))
  }

  // 获取共识详情
  await getLevelDetail()

  // 有未支付的订单
  if (detail.value?.transfer) {
    const { end_amount } = detail.value?.order
    const { recipient, open_amount } = detail.value?.transfer

    if (v === 'open') {
      // 激活共识
      return sendTransferBaseCoin(recipient, open_amount)
    } else if (v === 'finish') {
      // 完成共识
      return sendTransferBaseCoin(recipient, end_amount)
    } else {
      showToast($t('已有开启中的共识合约质押单'))
      return false
    }
  }

  const params = {
    level: v.level,
  }

  const { code } = await api.createLevelOrder(params)

  if (code === 1) {
    showToast($t('创建成功'))
    setTimeout(initPage, 2000)
  }
}

// 插件转账
async function sendTransferBaseCoin(toAddress, volume) {
  try {
    if (!toAddress || !volume) {
      return showToast($t('支付参数丢失，请联系客服'))
    }

    const isWallet = await cosmo.isWallet
    const isChrome = await cosmo.isChrome

    // 转账参数
    const params = {
      toAddress,
      volume,
      fee: '2000',
      scale: 6,
      denom: 'uplugcn',
      memo: `open_amount_${Date.now()}`,
    }

    params.volume = Number(params.volume + params.volume * 0.008).toFixed(6)

    console.log('转账参数：', params)

    // 加载中
    showLoading()

    // 返回结果
    let result = null

    if (isWallet) {
      result = await cosmo.sendTransferBaseCoin(params)
    } else if (isChrome) {
      result = await cosmo.chromeTool.sendTransferBaseCoin(
        params.toAddress,
        params.volume,
        params.memo
      )
    }

    console.log('转账结果：', result)

    if (result) {
      showToast($t('交易上链中'))
      setTimeout(initPage, 2000)
      setTimeout(getLevelDetail, 10000)
    } else {
      showToast($t('转账失败，请重试'))
      setTimeout(createLevelOrder, 2000)
    }
  } catch (err) {
    console.log('转账结果：', err)

    if (err && typeof err === 'string' && err.includes('error')) {
      showToast($t('密码错误，请重试'))
    } else {
      showToast($t('转账失败，请重试'))
    }
  }
}

// 开始倒计时
function startCountDown() {
  const up = detail.value?.level_info.up || 0

  if (startTime.value) {
    const nowTime = Date.now()
    const upTime = up * 1000 * 60 * 60 * 24
    endTime.value = startTime.value + upTime
    countTime.value = endTime.value - nowTime
  }
}

// 设计倒计时进度
function setCountProgress() {
  countProgress.value =
    ((Date.now() - startTime.value) / (endTime.value - startTime.value)) * 100
}

function getBalanceFirst(balance = 0) {
  const b = String(balance)
  return b.split('.')[0]
}

function getBalanceLast(balance = 0) {
  const b = String(balance)
  return b.split('.')[1]
}

function getLevelIconUrl(level) {
  return new URL(`../assets/img/icon_v${level}.png`, import.meta.url).href
}
</script>

<style lang="scss" scoped>
.page {
  background: #f3f5f6 url('../assets/img/bg.png') no-repeat left top / 100%;

  .address {
    padding: 10px 15px;
    border-radius: 100px;
    background-color: #0da656;
  }

  .tag {
    display: inline-block;
    padding: 5px 30px;
    border-radius: 100px;
    background-color: black;
    color: white;
  }

  :deep(.van-tabs) {
    .van-tabs__wrap {
      height: 40px;
      margin-bottom: 15px;
    }

    .van-tabs__nav {
      height: 40px;
      border: none;
      border-radius: 100px;
      background-color: var(--color-bg);
      margin: 0;
    }

    .van-tab {
      border-radius: 100px;
      border: none;
      color: var(--color-basic);

      &--active {
        color: white;
        background-color: black;
      }
    }
  }
}
</style>
